import com.troyworks.particleengine.Particle;
import com.troyworks.framework.ui.layout.Bounds2;
import flash.geom.Rectangle;
import com.troyworks.framework.ui.DraggableClip;
/**
 * @author Troy Gardner
 */
class com.troyworks.particleengine.Ch8_07 extends MovieClip {
	/* particle actual  position*/
	var p : Particle;
	/* target particle position*/
	var tp : Particle;

	/* velocity*/
	var v : Particle;
	/* acceleration */
	var a:Particle;
	
	var easing : Number = .1;
	var fl : Number = 250;
	var vpX : Number = _width/2;
	var vpY : Number = _height/2;
	var ball : DraggableClip;
	var bounds : Rectangle;
	//////////Forces ///////////
	var bounce : Number = 0.7;
	var gravity : Number = 5;
	var spring : Number = 0.1;
	var friction : Number = 0.97;

	public function Ch8_07() {
		trace("Ch8_07");
		p  = new Particle();
		tp  = new Particle();
		v = new Particle();		
		a = new Particle();
	}
	public function onLoad() : Void{
		trace("onLoad");
		bounds = new Rectangle();
		bounds.top = 0;
		bounds.left = 0;
		bounds.bottom =_height;
		bounds.right = _width;

		tp.x = bounds.left + bounds.width/2;
		tp.y =bounds.top + bounds.height/2;
		p.x = 10;
		p.y =10;
		ball._x = p.x;
		ball._y = p.y;

		v.x = Math.random() * 10 -5;
		v.y = Math.random() * 10 -5;
		
	}
	function onEnterFrame() : Void {
		if(!ball.isBeingDragged){
			//trace("onEnterFrame()" + util.Trace.me(p, "p1"));
				a.x = (tp.x - p.x) * spring;
				a.y = (tp.y - p.y) * spring;
				/////////integrte
				v.x += a.x;
				v.y += a.y;
				v.y += gravity;
				v.x *= friction;
				v.y *= friction;
	
			///////////////////////////
				p.x +=v.x;
				p.y +=v.y;
		//			trace("onEnterFrame()" + util.Trace.me(p, "p2"));
				var b : Bounds2 = new Bounds2(ball.getBounds(this));
			///////// check x ///////////////
			if(b.xMax > bounds.right){
					trace("hit R wall");
					p.x = bounds.right - b.width;
					v.x = Math.abs(v.x)*-1* bounce;
			}else if(b.xMin < bounds.left){
					trace("hit L wall");
					p.x = bounds.left + 1;// + b.width + 1;
					v.x = Math.abs(v.x) * bounce;
			}
			////////// check y ////////////////
			if( bounds.bottom -.9 < b.yMax && b.yMax < bounds.bottom +.9 && Math.abs(v.y) <1){
		//		trace("on Bottom");
			//	v.x = 0;
					v.y = -gravity;
			} else if(b.yMax >bounds.bottom){
					trace("hit Bottom yMax: " + b.yMax  + " bottom: " + bounds.bottom + " v: " + v.y);
	
					v.y= Math.abs(v.y* bounce)*-1;
					p.y -= (b.yMax- bounds.bottom) - v.y;
			}else if(b.yMin < bounds.top){
					trace("hit Top");
					p.y = bounds.top +1 ;//+ b.height;
					v.y= Math.abs(v.y* bounce);
			}
			///// update the clip /////////
				ball._x = p.x;
				ball._y = p.y;
		
		}else{
			v.x = ball._x - ball.lastX;
			v.y = ball._y - ball.lastY;
			p.x = ball._x;
			p.y = ball._y;
		}
				//////////// draw the line ///////////
				clear();
				lineStyle(1, 0, 100);
				moveTo(p.x, p.y);
				lineTo(tp.x,tp.y);
	}
}